package 序列化与反序列化;

import com.alibaba.fastjson.JSON;
import lombok.Data;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

@Data
public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    public static int id;
    private String name;
    private int age;
    private int height;
    private Pet pet;
    private transient Car car;

    public static void main(String[] args) {
        serializePerson();
        deserializePerson();
    }

    private static void serializePerson() {
        Person person = new Person();
        person.setName("张三三");
        person.setAge(18);
        person.setPet(new Pet("大黄"));
        person.setCar(new Car("奥迪"));
        Person.id = 1;
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.txt"))) {
            out.writeObject(person);
            System.out.println("序列化完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("JSON.toJSONString(person):"+JSON.toJSONString(person));
    }

    private static void deserializePerson() {
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.txt"))) {
            Person readObject = (Person) in.readObject();
            System.out.println("readObject = " + readObject);
            System.out.println(Person.id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
